package org.example.platform.beans.factory;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

public class Test2 {


    /**
     * 基于Cglib实线构造函数的类实例化策略
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 初始化BeanFactory
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        // 注入bean
        BeanDefinition beanDefinition = new BeanDefinition(UserService.class);
        beanFactory.registerBeanDefinition("userService",beanDefinition);
        // 获取bean
        UserService userService = (UserService) beanFactory.getBean("userService",new Object[]{"vrjo"});
        userService.queryUser();

        // 验证有构造函数实例化
        Class<UserService> userServiceClass = UserService.class;
        Constructor<UserService> userServiceConstructor  = userServiceClass.getDeclaredConstructor(String.class);
        UserService userService1 = userServiceConstructor.newInstance("test");
        System.out.println(userService1);

        // 获取构造函数信息
        Class<UserService> userServiceClass1 = UserService.class;
        // 获取传参类型
        Constructor<?>[] userServiceConstructor1  = userServiceClass1.getDeclaredConstructors();
        Constructor<?> constructor  = userServiceConstructor1[0];
        Constructor<UserService> userServiceConstructor2  = userServiceClass1.getDeclaredConstructor(constructor.getParameterTypes());
        UserService userService2 = userServiceConstructor2.newInstance("test222222222");
        System.out.println(userService2);

        // Cglib
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(UserService.class);
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        Object object = enhancer.create(new Class[]{String.class},new Object[]{"ceshi"});
        System.out.println(object);


    }
}
